<template>
    <n-drawer :show="active" :width="width" :mask-closable="false" @update:show="(flag:boolean) => (active = flag)">
        <n-drawer-content :native-scrollbar="false" title="分润设置" closable>
            <n-space vertical :size="24" v-if="model.type">
                <n-form label-placement="left" inline :show-feedback="false">
                    <n-form-item label="车辆信息">
                        <n-space>
                            <b>{{ item.cno }}</b>
                            <b>{{ item.name }}</b>
                        </n-space>
                    </n-form-item>
                </n-form>
                <n-form label-placement="left" :model="model" :rules="rules" ref="formRef">
                    <n-form-item label="分配方式" path="type">
                        <n-radio-group v-model:value="model.type" name="radiogroup">
                            <n-space>
                                <n-radio :value="1">全归门店</n-radio>
                                <n-radio :value="2">基础价格</n-radio>
                                <n-radio :value="3">租金比例</n-radio>
                            </n-space>
                        </n-radio-group>
                    </n-form-item>
                </n-form>
                <n-alert title="全归门店" type="info" v-if="model.type == 1">订单全部收入归门店所有</n-alert>

                <n-table :bordered="true" :single-line="true" v-if="model.type == 2">
                    <thead>
                        <tr>
                            <th width="25%"></th>
                            <th width="25%">名称</th>
                            <th width="25%">分配收入</th>
                            <th width="25%">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><b>基础价格</b></td>
                            <td>{{ model.rent.base.name }}</td>
                            <td>{{ (model.rent.base.amt / 100).toFixed(2) }} 元 / 天</td>
                            <td>
                                <n-space v-if="model.rent.spliter.length == 0">
                                    <n-button size="tiny" type="info" @click="() => doAddUser()">添加</n-button>
                                    <n-button size="tiny" type="error" @click="() => doDelUser()">删除</n-button>
                                </n-space>
                            </td>
                        </tr>
                        <tr v-for="(ser, idx) in model.rent.spliter">
                            <td><b>剩余租金</b></td>
                            <td>{{ ser.name }}</td>
                            <td>
                                <template v-if="ser.type == 1">{{ (ser.amt / 100).toFixed(2) }} 元 / 天</template>
                                <template v-if="ser.type == 2">{{ (ser.rate / 10).toFixed(1) }} %</template>
                            </td>
                            <td>
                                <n-space v-if="idx == model.rent.spliter.length - 1">
                                    <n-button size="tiny" type="info" @click="() => doAddUser()">添加</n-button>
                                    <n-button size="tiny" type="error" @click="() => doDelUser()">删除</n-button>
                                </n-space>
                            </td>
                        </tr>
                    </tbody>
                </n-table>

                <n-table :bordered="true" :single-line="true" v-if="model.type == 3">
                    <thead>
                        <tr>
                            <th width="25%"></th>
                            <th width="25%">名称</th>
                            <th width="25%">分配收入</th>
                            <th width="25%">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(ser, idx) in model.rate.spliter">
                            <td><b>剩余租金</b></td>
                            <td>{{ ser.name }}</td>
                            <td>{{ (ser.rate / 10).toFixed(1) }} %</td>
                            <td>
                                <n-space v-if="idx == model.rate.spliter.length - 1">
                                    <n-button size="tiny" type="info" @click="() => doAddUser()">添加</n-button>
                                    <n-button size="tiny" type="error" @click="() => doDelUser()">删除</n-button>
                                </n-space>
                            </td>
                        </tr>
                        <tr v-if="model.rate.spliter.length == 0">
                            <td><b>剩余租金</b></td>
                            <td>--</td>
                            <td>--</td>
                            <td>
                                <n-space>
                                    <n-button size="tiny" type="info" @click="() => doAddUser()">添加</n-button>
                                </n-space>
                            </td>
                        </tr>
                    </tbody>
                </n-table>
            </n-space>

            <template #footer>
                <n-space justify="end">
                    <n-button type="tertiary" :disabled="loading" @click="() => (active = false)">
                        <template #icon>
                            <n-icon :component="CloseRound" />
                        </template>
                        关闭
                    </n-button>

                    <n-button type="primary" :loading="loading" @click="execSave">
                        <template #icon>
                            <n-icon :component="CheckRound" />
                        </template>
                        提交保存
                    </n-button>
                </n-space>
            </template>
            <n-modal v-model:show="selectUser">
                <n-card style="width: 960px; height: 600px" title="选择人员" :bordered="false">
                    <n-space vertical>
                        <n-form label-placement="left" inline :show-feedback="false">
                            <n-form-item label="计算方式">
                                <n-radio-group v-model:value="userm.type" name="radiogroup">
                                    <n-space>
                                        <n-radio :value="1" v-if="model.type == 2" :disabled="userm.uid == 'share'">固定金额</n-radio>
                                        <n-radio :value="2">动态比例</n-radio>
                                    </n-space>
                                </n-radio-group>
                            </n-form-item>
                            <n-form-item v-if="userm.type == 1">
                                <DecimalInput :precision="2" :border="true" suffix="元" :min="0" v-model:base="userm.amt" />
                            </n-form-item>
                            <n-form-item v-if="userm.type == 2 && userm.uid != 'share'">
                                <DecimalInput :precision="1" :border="true" suffix="%" :max="100" :min="0" v-model:base="userm.rate" />
                            </n-form-item>
                        </n-form>

                        <n-tabs
                            type="line"
                            animated
                            @before-leave="(tab:string)=>{
                            if(tab == '3'){
                                userm.uid = 'mchid'
                                userm.name = '门店账户'
                            } else if(tab == '4'){
                                userm.uid = 'share'
                                userm.name = '获客人员'
                                userm.sort = 99999
                                userm.type = 2
                                userm.rate = 1000
                            } else {
                                userm.uid = ''
                                userm.name = ''
                            }
                        
                            return true
                        }"
                        >
                            <n-tab-pane name="1" tab="店内人员">
                                <n-scrollbar style="max-height: 350px">
                                    <n-list bordered>
                                        <n-list-item v-for="clk in clks">
                                            <template #suffix>
                                                <n-button
                                                    :type="userm.uid == clk.id ? 'info' : 'default'"
                                                    @click="
                                                        () => {
                                                            userm.uid = clk.id
                                                            userm.name = clk.name
                                                        }
                                                    "
                                                >
                                                    {{ userm.uid == clk.id ? '已选' : '选择' }}
                                                </n-button>
                                            </template>
                                            <n-thing :title="clk.name">
                                                <template #description>
                                                    <n-space>
                                                        <n-tag :bordered="false" size="small" type="info" v-if="clk.admin">管理员</n-tag>
                                                        <n-tag :bordered="false" size="small" type="warning" v-if="clk.manager">店长</n-tag>
                                                        <span>{{ clk.mob }}</span>
                                                    </n-space>
                                                </template>
                                            </n-thing>
                                        </n-list-item>
                                    </n-list>
                                </n-scrollbar>
                            </n-tab-pane>
                            <n-tab-pane name="2" tab="店外人员" v-if="model.type == 2">
                                <n-space vertical>
                                    <n-input-group>
                                        <n-input v-model:value="smob" :style="{ width: '300px' }" placeholder="请填写手机号查询合伙人信息" />
                                        <n-button type="primary" ghost @click="execQueryMem">搜索</n-button>
                                    </n-input-group>

                                    <n-space v-if="smem.id">
                                        已查询到：
                                        <b>{{ smem.name }} / {{ smem.mobile }}</b>
                                    </n-space>

                                    <n-space vertical v-if="schd && !smem.id">
                                        <b>未查询到已有用户，请填写合伙人信息</b>
                                        <n-form label-placement="left" :model="nmem" :rules="rules">
                                            <n-space vertical :size="24">
                                                <n-grid :cols="24" :x-gap="24">
                                                    <n-form-item-gi :span="24" label="人员名称" path="name">
                                                        <n-input v-model:value="nmem.name" placeholder="请填写人员名称" />
                                                    </n-form-item-gi>
                                                    <n-form-item-gi :span="24" label="身份证号" path="idno">
                                                        <n-input v-model:value="nmem.idno" placeholder="请填写身份证号" />
                                                    </n-form-item-gi>
                                                </n-grid>
                                            </n-space>
                                        </n-form>
                                    </n-space>
                                </n-space>
                            </n-tab-pane>
                            <n-tab-pane name="3" tab="门店账户">收入归门店账户</n-tab-pane>
                            <n-tab-pane name="4" tab="获客人员" v-if="model.type == 2 && model.rent.base.uid">收入归订单推广获客人员，获客人员顺位将默认至最后一位，且固定为比例模式，100%</n-tab-pane>
                        </n-tabs>
                    </n-space>
                    <template #footer>
                        <n-space justify="end">
                            <n-button
                                @click="
                                    () => {
                                        selectUser = false
                                    }
                                "
                            >
                                取消
                            </n-button>
                            <n-button type="success" @click="doEnterUser">确认</n-button>
                        </n-space>
                    </template>
                </n-card>
            </n-modal>
        </n-drawer-content>
    </n-drawer>
</template>

<script lang="ts" setup>
import { computed, ref, onBeforeMount } from 'vue'
import { CloseRound, CheckRound } from '@vicons/material'

import { Http } from '@/libs'
import { useStore } from '@/store'

import DecimalInput from '@/comp/func/DecimalInput.vue'

const store = useStore()
const width = computed(() => Math.max(store.state.browser.innerWidth * 0.4, 640))

const { $notification: notification } = window

const loading = ref(false)

const prop = defineProps({
    show: {
        type: Boolean,
        required: true,
    },
    item: {
        type: Object,
        default: {},
    },
})

const emit = defineEmits(['update:show', 'refresh'])

const active = computed({
    get: () => prop.show,
    set: val => emit('update:show', val),
})

const formRef = ref<any>(null)

const model = ref<any>({})

const rules = {
    name: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请填写人员名称',
    },
    idno: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请填写身份证号',
    },
}

const schd = ref<boolean>(false)
const smob = ref<any>('')
const smem = ref<any>({})
const nmem = ref<any>({})

const execQueryMem = () => {
    if (!smob.value) {
        notification.error({
            duration: 1500,
            title: '请填写人员手机号',
        })
        return
    }
    Http.post('/comm/biz/member/query', {
        mob: smob.value,
    }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        schd.value = true
        smem.value = resp.data
        if (resp.data.id) {
            userm.value.uid = resp.data.id
            userm.value.name = resp.data.name
        } else {
            userm.value.uid = ''
            userm.value.name = ''
        }
    })
}

const clks = ref<any>([])

const selectUser = ref<boolean>(false)

const userm = ref<any>({})

const execLoadClerks = () => {
    clks.value = []

    Http.post('/ops/biz/merchant/clerk/list', {
        id: prop.item.merchant.id,
    }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        clks.value = resp.data.items
    })
}
const doAddUser = () => {
    userm.value = {
        type: model.value.type - 1,
        name: '',
        uid: '',
        sort: 0,
        amt: 0,
        rate: 0,
    }
    smob.value = ''
    smem.value = {}
    schd.value = false
    nmem.value = {}
    selectUser.value = true
}

const doEnterUser = () => {
    if (!userm.value.uid && (!nmem.value.name || !nmem.value.idno || !smob.value)) {
        notification.error({
            duration: 1500,
            title: '请选择分配人员',
        })
        return
    }
    if (userm.value.type == 1 && userm.value.amt == 0) {
        notification.error({
            duration: 1500,
            title: '请填写分配金额',
        })
        return
    }
    if (userm.value.type == 2 && userm.value.rate == 0) {
        notification.error({
            duration: 1500,
            title: '请填写分配比例',
        })
        return
    }
    if (!userm.value.uid) {
        Http.post('/comm/biz/member/create', {
            mob: smob.value,
            name: nmem.value.name,
            idno: nmem.value.idno,
        }).then(resp => {
            if (resp.stat.err > 0) {
                return
            }
            userm.value.uid = resp.data.id
            userm.value.name = nmem.value.name

            if (model.value.type == 2) {
                if (!model.value.rent.base.uid) {
                    model.value.rent.base = {
                        uid: userm.value.uid,
                        name: userm.value.name,
                        amt: userm.value.amt,
                    }
                } else {
                    let spliter = model.value.rent.spliter
                    spliter[spliter.length] = {
                        uid: userm.value.uid,
                        type: userm.value.type,
                        amt: userm.value.amt,
                        name: userm.value.name,
                        rate: userm.value.rate,
                        sort: userm.value.uid == 'share' ? userm.value.sort : spliter.length,
                    }
                    spliter.sort((m: any, n: any) => {
                        return m.sort - n.sort
                    })
                    model.value.rent.spliter = spliter
                }
            } else if (model.value.type == 3) {
                model.value.rate.spliter[model.value.rate.spliter.length] = {
                    uid: userm.value.uid,
                    name: userm.value.name,
                    rate: userm.value.rate,
                    sort: model.value.rate.spliter.length,
                }
            }
            selectUser.value = false
        })
    } else {
        if (model.value.type == 2) {
            if (!model.value.rent.base.uid) {
                model.value.rent.base = {
                    uid: userm.value.uid,
                    name: userm.value.name,
                    amt: userm.value.amt,
                }
            } else {
                let spliter = model.value.rent.spliter
                spliter[spliter.length] = {
                    uid: userm.value.uid,
                    type: userm.value.type,
                    amt: userm.value.amt,
                    name: userm.value.name,
                    rate: userm.value.rate,
                    sort: userm.value.uid == 'share' ? userm.value.sort : spliter.length,
                }
                spliter.sort((m: any, n: any) => {
                    return m.sort - n.sort
                })
                model.value.rent.spliter = spliter
            }
        } else if (model.value.type == 3) {
            model.value.rate.spliter[model.value.rate.spliter.length] = {
                uid: userm.value.uid,
                name: userm.value.name,
                rate: userm.value.rate,
                sort: model.value.rate.spliter.length,
            }
        }
        selectUser.value = false
    }
}

const doDelUser = () => {
    if (model.value.type == 2) {
        if (model.value.rent.spliter.length > 0) {
            model.value.rent.spliter.length = model.value.rent.spliter.length - 1
        } else if (model.value.rent.base.uid) {
            model.value.rent.base = {
                uid: '',
                name: '',
                amt: 0,
            }
        }
    } else if (model.value.type == 3) {
        model.value.rate.spliter.length = model.value.rate.spliter.length - 1
    }
}

const execReset = () => {
    model.value = JSON.parse(JSON.stringify(prop.item.settle))
}

const execSave = (e: Event) => {
    if (model.value.type == 2) {
        if (model.value.rent.base.amt <= 0 || !model.value.rent.base.uid) {
            notification.error({
                duration: 1500,
                title: '请指定分润人员',
            })
            return
        }
    }
    if (model.value.type == 3) {
        if (model.value.rate.spliter.length == 0) {
            notification.error({
                duration: 1500,
                title: '请指定分润人员',
            })
            return
        }

        let max = model.value.rate.spliter.reduce((p: any, c: any) => p + c.rate, 0)
        if (max != 1000) {
            notification.error({
                duration: 1500,
                title: '请设置正确的租金分配比例',
            })
            return
        }
    }
    let i = 1
    let k = 1
    let body = {
        type: model.value.type,
        rate: {
            spliter: model.value.rate.spliter.map((spliter: any) => {
                return {
                    rate: spliter.rate,
                    uid: spliter.uid,
                    sort: k++,
                }
            }),
        },
        rent: {
            base: model.value.rent.base,
            spliter: model.value.rent.spliter.map((spliter: any) => {
                return {
                    amt: spliter.amt,
                    rate: spliter.rate,
                    uid: spliter.uid,
                    type: spliter.type,
                    sort: i++,
                }
            }),
        },
    }

    e.preventDefault()
    formRef.value.validate((errors: any[]) => {
        if (!errors) {
            loading.value = true
            Http.post('/ops/biz/car/settle/set', {
                id: prop.item.id,
                settle: body,
            }).then(resp => {
                if (resp.stat.err > 0) {
                    loading.value = false
                    return
                }
                emit('refresh', {})
                notification.success({
                    duration: 1500,
                    title: '操作成功',
                    content: '您已成功保存分润配置',
                })
                setTimeout(() => {
                    loading.value = false
                    emit('update:show', false)
                }, 200)
            })
        } else {
            let msgs = errors.map(err => err[0].message)
            notification.error({
                duration: 1500,
                title: '请填写完整内容',
                description: '当前表单存在以下问题，请处理后提交',
                content: msgs.join('\n'),
            })
        }
    })
}
onBeforeMount(() => {
    execReset()
    execLoadClerks()
})
</script>
